﻿import { cloneDeep } from 'lodash-es'

// 通过对象的值，获取指定的key
export const getObjKey = (Obj, val) => {
  let currentKey = ''
  for (const key in Obj) {
    if (val === Obj[key]) {
      currentKey = key
      break
    }
  }
  return currentKey
}

// 随机获取图片地址
export const getRandomImageUrl = (type) => {
  const typeList = ['landscape', 'animal', 'food', 'beauty', 'car', 'cartoon', 'game', 'other']
  const randomEnd = 115
  let currentType = ''
  let currentRandomNum = 0
  if (type !== '') {
    currentType = type
  } else {
    currentType = typeList[randomNum(0, typeList.length - 1)]
  }
  currentRandomNum = randomNum(1, randomEnd)
  return 'https://cdn.jsdelivr.net/gh/kaivin/images/list/' + currentType + '/' + currentRandomNum + '.jpg'
}

// 生成指定范围内的随机数
export const randomNum = (min, max) => {
  return Math.floor(Math.random() * (max - min) + min)
}

/**
 * 两个对象的深度合并
 */
export const deepMerge = (obj1, obj2) => {
  let key
  for (key in obj2) {
    // 如果target(也就是obj1[key])存在，且是对象的话再去调用deepMerge，否则就是obj1[key]里面没这个对象，需要与obj2[key]合并
    // 如果obj2[key]没有值或者值不是对象，此时直接替换obj1[key]
    obj1[key] = obj1[key] && obj1[key].toString() === '[object Object]' && obj2[key] && obj2[key].toString() === '[object Object]' ? deepMerge(obj1[key], obj2[key]) : (obj1[key] = obj2[key])
  }
  return obj1
}

// 正序排列
export function sortByAsc(i) {
  return function (a, b) {
    return a[i] - b[i]
  }
}

// 倒序排列
export function sortByDesc(i) {
  return function (a, b) {
    return b[i] - a[i]
  }
}

// eslint-disable-next-line no-undef
export function openWindow(url: string, opt?: { target?: TargetContext | string; noopener?: boolean; noreferrer?: boolean }) {
  const { target = '__blank', noopener = true, noreferrer = true } = opt || {}
  const feature: string[] = []

  noopener && feature.push('noopener=yes')
  noreferrer && feature.push('noreferrer=yes')

  window.open(url, target, feature.join(','))
}

export function strPlaceholderFormat(str, args) {
  for (let i = 0; i < args.lenght; i++) {
    str = str.replace(new RegExp('\\{' + i + '\\}', 'g'), i)
  }
  return str
}

// 数据转化为树结构
export const dataToTree = (data, pid, pidKey, key) => {
  const parents = data.filter(function (item: any) {
    return item[pidKey] === pid
  })
  const children = data.filter(function (item: any) {
    return item[pidKey] !== pid
  })
  // 递归处理动态路由层级
  treeConvert(parents, children, pidKey, key)
  return parents
}

const treeConvert = (parents, children, pidKey, key) => {
  parents.forEach(function (item: any) {
    item.children = []
    children.forEach(function (current: any, index: any) {
      if (current[pidKey] === item[key]) {
        const temp = children.filter(function (v: any, idx: any) {
          return idx !== index
        }) // 删除已匹配项
        item.children.push(current)
        treeConvert([current], temp, pidKey, key) // 递归
      }
    })
  })
}

// 树结构数据添加线条结构
export const treeData = (data, isLast, hideLine, level) => {
  data.forEach((item, index) => {
    item.level = level + 1
    if (index === 0) {
      item.isFirst = true
    } else {
      item.isFirst = false
    }
    if (index === data.length - 1) {
      item.isLast = true
    } else {
      item.isLast = false
    }
    item.hideLine = cloneDeep(hideLine)
    if (isLast) {
      item.hideLine.push(item.level - 1)
    }
    if (item.children && item.children.length > 0) {
      treeData(item.children, item.isLast, item.hideLine, item.level)
    }
  })
}

// 格式化树结构的关键key、value
export const treeFormat = (data, key, value) => {
  data.forEach((item: any) => {
    item.label = item[key]
    item.value = item[value]
    if (item.children && item.children.length > 0) {
      treeFormat(item.children, key, value)
    }
  })
}

/**
 * * JSON序列化，支持函数和 undefined
 * @param data
 */
export const JSONStringify = <T>(data: T) => {
  return JSON.stringify(
    data,
    (key, val) => {
      // 处理函数丢失问题
      if (typeof val === 'function') {
        return `${val}`
      }
      // 处理 undefined 丢失问题
      if (typeof val === 'undefined') {
        return null
      }
      return val
    },
    2
  )
}
